<?php
/**
 * Created by PhpStorm.
 * User: CLAKE
 * Date: 2016/7/26
 * Time: 5:01
 */

namespace CK\Cache;


use CK\Util\IO\Directory;
use CK\Util\IO\File;

/**
 * 文件缓存功能
 * Class Filecached
 * @package CK\Cache
 */
class Filecached extends Cache {

    private $_conf = [
        //文件目录
        'file_dir'=>'../cache/file_cache/',
        'prefix'=>'ck_'
    ];

    public function __construct($conf=null) {
        if ($conf) {
            $this->_conf = $conf;
        }
        if (!Directory::Exists($this->_conf['file_dir'])) {
            Directory::Create($this->_conf['file_dir']);
        }
    }

    /**
     * 得到KEY的缓存值
     * @param $key
     * @return mixed|null
     */
    public function get($key) {
        $name = $this->buildName($key);
        if (File::Exists($this->_conf['file_dir'].$name)) {
            $cache = include $this->_conf['file_dir'].$name;
            $value = false;
            if ($cache['expire'] > 0) {
                if ($cache['start_date']+$cache['expire'] < CK_NOW) {
                    File::Delete($this->_conf['file_dir'].$name);
                } else {
                    $value = unserialize($cache['value']);
                }
            } else {
                $value = unserialize($cache['value']);
            }
            return $value;
        } else {
            return false;
        }
    }

    /**
     * 设置KEY的缓存值
     * @param $key
     * @param $value
     * @param int $expire
     * @return int
     */
    public function set($key, $value, $expire = 300) {
        $name = $this->buildName($key);
        $cache = [
            'key'=>$key,
            'start_date'=>CK_NOW,
            'expire'=>$expire,
            'value'=>serialize($value)
        ];
        $content = var_export($cache,true);
        $content = "<?php \n return ".$content.';';
        return File::Write($this->_conf['file_dir'].$name,$content);
    }

    /**
     * 删除一个缓存
     * @param $key
     * @param int $timeout
     */
    public function delete($key, $timeout = 0) {
        $name = $this->buildName($key);
        return File::Delete($this->_conf['file_dir'].$name);
    }

    private function buildName($key) {
        return $this->_conf['prefix'].md5($key).'.cache';
    }
}